package com.cskaoyan.gateway.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.pay.PayForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.IUserQueryService;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : xfeng
 * @time : 2021/8/30 18:52
 * @program: myproject3
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("cashier")
@Api(tags = "PayController", description = "支付层")
public class PayController {

    @Reference(timeout = 20000, check = false)
    private PayCoreService payCoreService;

    @Reference(timeout = 20000, check = false)
    private IUserQueryService iUserQueryService;

    @PostMapping("pay")
    @ApiOperation("获取支付二维码")
    public ResponseData pay(@RequestBody PayForm payForm, HttpServletRequest servletRequest) {
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        //Json字符串转换为Json对象
        JSONObject object = JSON.parseObject(userInfo);
        long userId = Long.parseLong(object.get("uid").toString());

        PaymentRequest request = new PaymentRequest();
        request.setUserId(userId);
        request.setTradeNo(payForm.getOrderId());
        request.setTotalFee(payForm.getMoney());
        request.setOrderFee(payForm.getMoney());
        request.setSubject(payForm.getInfo());
        request.setPayChannel(payForm.getPayType());
        String username = iUserQueryService.queryUser(userId);
        request.setUsername(username);

        AlipaymentResponse response = payCoreService.aliPay(request);

        if (response.getCode().equals(PayReturnCodeEnum.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getQrCode());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @GetMapping("queryStatus")
    @ApiOperation("查询支付状态")
    public ResponseData queryStatus(String orderId) {
        PaymentRequest request = new PaymentRequest();
        request.setTradeNo(orderId);
        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(request);

        if (response.getCode().equals(PayReturnCodeEnum.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

}
